/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * LaneErrorPanel.java
 *
 * Created on 07-12-2011, 09:02:35
 */
package GUILag;

import ControllerLag.LaneErrorCTR;
import ModelLag.LaneError;
import java.util.Date;
import java.util.GregorianCalendar;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;

/**
 * Denne klasse bruges for at oprette en fejl ud fra en dato, som kan ses i en tabel i LaneErrorGUI.
 * @author DM75 Gruppe 3.
 * @version 22-12-2011.
 */
public class LaneErrorGUI extends javax.swing.JFrame {
    private GregorianCalendar date;
    private LaneErrorCTR LECTR;
    private ArrayList<LaneError> laneErrors;
    private static LaneErrorGUI _instance = null; // singleton
    private boolean debug = false;

    private LaneErrorGUI(){
        initComponents();
        LECTR = new LaneErrorCTR();
        date = new GregorianCalendar();
        setDateField();
        updateTable();
        laneErrors = new ArrayList<>();
        laneErrorCalenderjTable1.getColumnModel().getColumn(1).setPreferredWidth(80);
        laneErrorCalenderjTable1.getColumnModel().getColumn(3).setPreferredWidth(50);
        laneErrorCalenderjTable1.getColumnModel().getColumn(4).setPreferredWidth(50);
        laneErrorCalenderjTable1.getColumnModel().getColumn(6).setPreferredWidth(300);
        laneErrorCalenderjTable1.addMouseListener(new MouseAdapter()
        {
            public void mouseReleased(MouseEvent e)
            {
                if(e.isPopupTrigger())
                {
                    JTable source = (JTable)e.getSource();
                    int row = source.rowAtPoint(e.getPoint());
                    int column =  source.columnAtPoint(e.getPoint());
                    
                    if(! source.isRowSelected(row))
                        source.changeSelection(row, column, false, false);
                    jPopupMenu1.show(e.getComponent(), e.getX(), e.getY());
                }
            }
        });
        
        }
    
    public static LaneErrorGUI getInstance()
    {
        if(null == _instance)
        {
            _instance = new LaneErrorGUI();
        }
        return _instance;
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane2 = new javax.swing.JScrollPane();
        jTable2 = new javax.swing.JTable();
        jPopupMenu1 = new javax.swing.JPopupMenu();
        deleteLaneErrorjMenuItem1 = new javax.swing.JMenuItem();
        BaneFejljLabel1 = new javax.swing.JLabel();
        lastYearjButton1 = new javax.swing.JButton();
        nextYearjButton3 = new javax.swing.JButton();
        dateLabel = new javax.swing.JLabel();
        seekjTextField1 = new javax.swing.JTextField();
        seekjButton2 = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        laneErrorCalenderjTable1 = new javax.swing.JTable();
        jButton1 = new javax.swing.JButton();

        jTable2.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        jScrollPane2.setViewportView(jTable2);

        deleteLaneErrorjMenuItem1.setText("Slet Bane Fejl");
        deleteLaneErrorjMenuItem1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                deleteLaneErrorjMenuItem1ActionPerformed(evt);
            }
        });
        jPopupMenu1.add(deleteLaneErrorjMenuItem1);

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusGained(java.awt.event.FocusEvent evt) {
                formFocusGained(evt);
            }
        });

        BaneFejljLabel1.setFont(new java.awt.Font("Tahoma", 0, 36));
        BaneFejljLabel1.setText("Bane Fejl");

        lastYearjButton1.setText("<<");
        lastYearjButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                lastYearjButton1ActionPerformed(evt);
            }
        });

        nextYearjButton3.setText(">>");
        nextYearjButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                nextYearjButton3ActionPerformed(evt);
            }
        });

        dateLabel.setText("2011");

        seekjTextField1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                seekjTextField1ActionPerformed(evt);
            }
        });

        seekjButton2.setText("Søg");
        seekjButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                seekjButton2ActionPerformed(evt);
            }
        });

        laneErrorCalenderjTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Dag", "Dato", "Tidspunkt", "Fejl Kode", "Bane Nr", "Medarbejder", "Beskrivelse"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.String.class, java.util.Date.class, java.lang.String.class, java.lang.String.class, java.lang.Integer.class, java.lang.String.class, java.lang.String.class
            };
            boolean[] canEdit = new boolean [] {
                false, false, false, false, false, false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        laneErrorCalenderjTable1.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        laneErrorCalenderjTable1.getTableHeader().setReorderingAllowed(false);
        laneErrorCalenderjTable1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                laneErrorCalenderjTable1MouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(laneErrorCalenderjTable1);

        jButton1.setText("Luk");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 828, Short.MAX_VALUE)
                    .addComponent(BaneFejljLabel1)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(seekjTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 166, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(seekjButton2)
                        .addGap(18, 18, 18)
                        .addComponent(lastYearjButton1)
                        .addGap(18, 18, 18)
                        .addComponent(dateLabel)
                        .addGap(18, 18, 18)
                        .addComponent(nextYearjButton3))
                    .addComponent(jButton1, javax.swing.GroupLayout.Alignment.TRAILING))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(BaneFejljLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, 44, Short.MAX_VALUE)
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(seekjTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(seekjButton2))
                        .addGap(36, 36, 36))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(lastYearjButton1)
                        .addComponent(dateLabel)
                        .addComponent(nextYearjButton3)))
                .addGap(18, 18, 18)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 371, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(8, 8, 8)
                .addComponent(jButton1)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents
  
    private void lastYearjButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_lastYearjButton1ActionPerformed
        setPreviousMonthYear(); 
        getModel().setRowCount(0);
        updateTable();
    }//GEN-LAST:event_lastYearjButton1ActionPerformed

    private void nextYearjButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_nextYearjButton3ActionPerformed
        setNextMonthYear();
        getModel().setRowCount(0);
        updateTable();
    }//GEN-LAST:event_nextYearjButton3ActionPerformed

    private void seekjButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_seekjButton2ActionPerformed
        //ddLaneErrorIntoTable(seekjTextField1.getText());       
    }//GEN-LAST:event_seekjButton2ActionPerformed

    private void seekjTextField1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_seekjTextField1ActionPerformed
        
    }//GEN-LAST:event_seekjTextField1ActionPerformed
      
    private void deleteLaneErrorjMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_deleteLaneErrorjMenuItem1ActionPerformed
        int selectedRow = laneErrorCalenderjTable1.getSelectedRow();
        if(laneErrorCalenderjTable1.getValueAt(selectedRow, 5) != null)
        {
            int input = JOptionPane.showConfirmDialog(this, "Er du sikker på du vil slette?", "Bekræft sletning ", JOptionPane.OK_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE);
                if(input == JOptionPane.OK_OPTION)
                {
                    int index = selectedRow;
                    while(laneErrorCalenderjTable1.getValueAt(index, 1) == null)
                    {
                        index--;
                    }
                    GregorianCalendar newDate = new GregorianCalendar();
                    newDate.setTime((Date)laneErrorCalenderjTable1.getValueAt(index, 1));
                    
                    int laneNo = (Integer) getModel().getValueAt(selectedRow, 4);
                    String errorCode = (String) getModel().getValueAt(selectedRow, 3);
                    
                    String time = (String) getModel().getValueAt(selectedRow, 2);
                    
                    int result = LECTR.deleteLaneError(laneNo, errorCode, newDate, time);
                    if(result == 1)
                    {
                        JOptionPane.showMessageDialog(this, "Sletning er fuldført", "sletning lykkes", JOptionPane.INFORMATION_MESSAGE);
                        getModel().removeRow(laneErrorCalenderjTable1.getSelectedRow());
                       // getModel().removeRow(laneErrorCalenderjTable1.convertColumnIndexToModel(selectedRow));
                        
                    }
                }
        }
        else
        {
            JOptionPane.showMessageDialog(this, "Du skal vælge en fejl", "Hvad vil du ?", JOptionPane.INFORMATION_MESSAGE);
        }
    }//GEN-LAST:event_deleteLaneErrorjMenuItem1ActionPerformed

    private void laneErrorCalenderjTable1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_laneErrorCalenderjTable1MouseClicked
        
        int selectedRow = laneErrorCalenderjTable1.getSelectedRow();
        
        Date dateInTable = (java.util.Date) laneErrorCalenderjTable1.getValueAt(selectedRow, 1);
        if(debug)
        {
            System.out.println("test1.2");
            System.out.println(dateInTable);
        }
        
        if(evt.getClickCount() == 2 && dateInTable != null)
        {
            if(debug)
            {
                System.out.println("test1.1");
            }
            CreateLaneErrorGUI createLaneErrorGUI = new CreateLaneErrorGUI(this);
            createLaneErrorGUI.setLocation(500, 100);
            createLaneErrorGUI.setVisible(true);
            this.setEnabled(false);
        }
        else if(evt.getClickCount() == 2 && dateInTable == null)
        {
            JOptionPane.showMessageDialog(this, "Dobblet klik på en dato for at tilføje en fejl. Højre Klik hvis du vil slette en fejl.", "Hvad vil du?", JOptionPane.INFORMATION_MESSAGE);;
        }
    
    }//GEN-LAST:event_laneErrorCalenderjTable1MouseClicked

    private void formFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_formFocusGained
        updateTable();
    }//GEN-LAST:event_formFocusGained

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        this.dispose();
    }//GEN-LAST:event_jButton1ActionPerformed

    public int getSelectedRow()
    {
        return laneErrorCalenderjTable1.getSelectedRow();
    }
    
    // Henter den dato som er markeret i tabellen.
    public Date getDateInTable()
    {
        int selectedRow = laneErrorCalenderjTable1.getSelectedRow();
        return (java.util.Date) laneErrorCalenderjTable1.getValueAt(selectedRow, 1);
    }
    
    // Henter den ugedag som er markeret i tabellen.
    public String getWeekDay()
    {
        int selectedRow = laneErrorCalenderjTable1.getSelectedRow();
        return (String) laneErrorCalenderjTable1.getValueAt(selectedRow, 0);
    }
    
    public void addLaneErrors(GregorianCalendar date)
    {
        boolean found = false;
        int index = 0;
        while(index < laneErrors.size() && !found)
        {
            if(laneErrors.get(index).getDate().equals(date))
            {
                found = true;
            }
            else
            {
            index++;
            }
        }
        if(found)
        {
            LaneError laneErrObj = laneErrors.get(index);
                String errorCode = "";
                String time = "";
                int laneNo;
                String name = "";
                String description = "";
                    for(LaneError laneErrorObj : laneErrors)
                        {
                            GregorianCalendar newdate = laneErrorObj.getDate();
                            if(debug)
                            {
                                System.out.println(laneErrorObj.getDate());
                            }
                            if(laneErrorObj.getDate().equals(date))
                            {
                            errorCode = laneErrorObj.getErrorCode();   
                            time = laneErrorObj.getTime();
                            newdate = laneErrorObj.getDate(); 
                            laneNo = laneErrorObj.getLane().getLaneNo();
                            name = laneErrorObj.getEmployee().getfName() + " " + laneErrorObj.getEmployee().getlName();
                            description = laneErrorObj.getDescription();

                            Object[] data = {null, null, time, errorCode ,laneNo, name, description };
                            getModel().addRow(data);
                            }
                        }
                    laneErrors.remove(index);
        }
    }
    /**
     * Henter alle datoer som er i den måned og år som er angivet i parameteren.
     * @param month
     * @param year
     * @return 
     */
    public Date[] getDatesThisMonth(int month, int year)
    {
        int firstDayInMonth = 1;
        
        GregorianCalendar firstDateInMonth = new GregorianCalendar(year, month-1, firstDayInMonth);
        
        int lastDayInMonth = firstDateInMonth.getActualMaximum(firstDateInMonth.DAY_OF_MONTH);
        Date[] datesInThisMonth = new Date[lastDayInMonth];
        
        while(firstDayInMonth <= lastDayInMonth)
        {
            Date newDate = firstDateInMonth.getTime();
            datesInThisMonth[firstDayInMonth -1] = newDate;
            firstDateInMonth.add(firstDateInMonth.DAY_OF_MONTH, 1);
            firstDayInMonth++;
        }

        return datesInThisMonth;
    }
    
    /**
     * henter uge dagene
     * @param weekDayNumb
     * @return 
     */
    public String getWeekDay(int weekDayNumb)
    {
        String weekday = "";
        switch(weekDayNumb)
        {
            case 1:
                weekday = "Søndag";
                break;
                
            case 2:
                weekday = "Mandag";
                break;
                
            case 3:
                weekday = "Tirsdag";
                break;
                
            case 4:
                weekday = "Onsdag";
                break;
                
            case 5:
                weekday = "Torsdag";
                break;
                
            case 6:
                weekday = "Fredag";
                break;
                
            case 7:
                weekday = "Lørdag";
                break;
        }

        return weekday;
    }
    
    public void setDateField()
    {
        dateLabel.setText(getInitialMonthYear());
    }
    
    /**
     * Henter den måned som det er, når programmet starter op.
     * @return 
     */
    public String getInitialMonthYear()
    {
        int month = date.get(date.MONTH)+1;
        String monthS = "";
        if(month < 10)
        {
            monthS = "0" + month;
        }
        else
        {
            monthS = "" + month;
        }
            
        String yearS = "" + (date.get(date.YEAR));   
        return monthS + "-" + yearS;
    }
    
    /**
     * sætter næste mdr.
     */
    public void setNextMonthYear()
    {
        date.add(date.MONTH, 1);
        setDateField();
    }
    /**
     * sætter til forrig måned
     */
    public void setPreviousMonthYear()
    {
        date.add(date.MONTH, -1);
        setDateField();
    }
    
    public void updateTable()
    {
        addWeekDayAndDateToTable(dateLabel.getText());
    }
   
    public DefaultTableModel getModel()
    {
        return (DefaultTableModel) laneErrorCalenderjTable1.getModel();
    }
    public void updateRow()
    {
        
    }
    
    private void addWeekDayAndDateToTable(String monthYear)
    {
        getModel().setRowCount(0);
        int month = Integer.parseInt(monthYear.substring(0, 2));
        int year = Integer.parseInt(monthYear.substring(3, 7));
        
        laneErrors = LECTR.getLaneErrorsMonth(month, year, true);
        
        Date datesThisMonth[] = getDatesThisMonth(month, year);
        
        String weekDay = "";
        Date newDate = null;
        GregorianCalendar date = new GregorianCalendar();
        
        int index = 0;
        while(index < datesThisMonth.length)
        {
            newDate = datesThisMonth[index];
            date.setTime(newDate);
            weekDay = getWeekDay(date.get(date.DAY_OF_WEEK));
   
            Object[] data = {weekDay, newDate};
            
            getModel().addRow(data);
            //Laver et kald ned til Datebasen for hver dato, det resultere i mange kald - 30 ialt - derfor bruges den anden metode.
            //addLaneErrorIntoTable(date);
            
            //Laver et kald ned til databasen for hver måned - 1 kald.
            addLaneErrors(date);
            index++;
        }
        
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel BaneFejljLabel1;
    private javax.swing.JLabel dateLabel;
    private javax.swing.JMenuItem deleteLaneErrorjMenuItem1;
    private javax.swing.JButton jButton1;
    private javax.swing.JPopupMenu jPopupMenu1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JTable jTable2;
    private javax.swing.JTable laneErrorCalenderjTable1;
    private javax.swing.JButton lastYearjButton1;
    private javax.swing.JButton nextYearjButton3;
    private javax.swing.JButton seekjButton2;
    private javax.swing.JTextField seekjTextField1;
    // End of variables declaration//GEN-END:variables
}
